/**
# Copyright (C) 2024 HiHope Open Source Organization .
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
 */

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "securec.h"
#include "sle_common.h"
#include "osal_debug.h"
#include "sle_errcode.h"
#include "osal_addr.h"
#include "osal_task.h"
#include "sle_connection_manager.h"
#include "sle_device_discovery.h"
#include "sle_uart_server_adv.h"
#include "sle_uart_server.h"
#include "cmsis_os2.h"
#include "ohos_init.h"
#include "ohos_sle_common.h"
#include "ohos_sle_errcode.h"
#include "ohos_sle_ssap_server.h"
#include "ohos_sle_ssap_client.h"
#include "ohos_sle_device_discovery.h"
#include "ohos_sle_connection_manager.h"
#include "iot_uart.h"
#include "pinctrl.h"
#include "uart.h"
#include "errcode.h"

#define OCTET_BIT_LEN 8
#define UUID_LEN_2 2
#define UUID_INDEX 14
#define BT_INDEX_4     4
#define BT_INDEX_0     0
#define UART_BUFF_LENGTH    0x100


static unsigned char modbusRequest[] = {0x01, 0x03, 0x00, 0x02, 0x00, 0x01, 0x25, 0xCA}; /*Modbus 请求帧*/
static uint8_t uart1ReadBuff[128]; /*接收缓冲区*/

/* 广播ID */
#define SLE_ADV_HANDLE_DEFAULT                    1
/* sle server app uuid for test */
static char g_sle_uuid_app_uuid[UUID_LEN_2] = { 0x12, 0x34 };
/* server notify property uuid for test */
static char g_sle_property_value[OCTET_BIT_LEN] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
/* sle connect acb handle */
static uint16_t g_sle_conn_hdl = 0;
/* sle server handle */
static uint8_t g_server_id = 0;
/* sle service handle */
static uint16_t g_service_handle = 0;
/* sle ntf property handle */
static uint16_t g_property_handle = 0;
/* sle pair acb handle */
uint16_t g_sle_pair_hdl;

// 定义了一些宏和日志打印函数
#define UUID_16BIT_LEN 2
#define UUID_128BIT_LEN 16
#define sample_at_log_print(fmt, args...) osal_printk(fmt, ##args)
#define SLE_UART_SERVER_LOG "[sle uart server]"
#define SLE_SERVER_INIT_DELAY_MS    1000
static sle_uart_server_msg_queue g_sle_uart_server_msg_queue = NULL;
static uint8_t g_sle_uart_base[] = { 0x37, 0xBE, 0xA8, 0x80, 0xFC, 0x70, 0x11, 0xEA, \
    0xB7, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
static uint8_t g_at_pre_char = 0;
static uint32_t g_at_uart_recv_cnt = 0;

#define SLE_UART_TRANSFER_SIZE              256
static uint8_t g_app_uart_rx_buff[SLE_UART_TRANSFER_SIZE] = { 0 };

static uart_buffer_config_t g_app_uart_buffer_config = {
    .rx_buffer = g_app_uart_rx_buff,
    .rx_buffer_size = SLE_UART_TRANSFER_SIZE
};



// 以下是一些工具函数，用于处理UUID和日志打印
static void encode2byte_little(uint8_t *_ptr, uint16_t data)
{
    *(uint8_t *)((_ptr) + 1) = (uint8_t)((data) >> 0x8);
    *(uint8_t *)(_ptr) = (uint8_t)(data);
}

static void sle_uuid_set_base(SleUuid *out)
{
    errcode_t ret;
    ret = memcpy_s(out->uuid, SLE_UUID_LEN, g_sle_uart_base, SLE_UUID_LEN);
    if (ret != EOK) {
        sample_at_log_print("%s sle_uuid_set_base memcpy fail\n", SLE_UART_SERVER_LOG);
        out->len = 0;
        return ;
    }
    out->len = UUID_LEN_2;
}

static void sle_uuid_setu2(uint16_t u2, SleUuid *out)
{
    sle_uuid_set_base(out);
    out->len = UUID_LEN_2;
    encode2byte_little(&out->uuid[UUID_INDEX], u2);
}
static void sle_uart_uuid_print(SleUuid *uuid)
{
    if (uuid == NULL) {
        sample_at_log_print("%s uuid_print,uuid is null\r\n", SLE_UART_SERVER_LOG);
        return;
    }
    if (uuid->len == UUID_16BIT_LEN) {
        sample_at_log_print("%s uuid: %02x %02x.\n", SLE_UART_SERVER_LOG,
            uuid->uuid[14], uuid->uuid[15]); /* 14 15: uuid index */
    } else if (uuid->len == UUID_128BIT_LEN) {
        sample_at_log_print("%s uuid: \n", SLE_UART_SERVER_LOG); /* 14 15: uuid index */
        sample_at_log_print("%s 0x%02x 0x%02x 0x%02x \n", SLE_UART_SERVER_LOG, uuid->uuid[0], uuid->uuid[1],
            uuid->uuid[2], uuid->uuid[3]);
        sample_at_log_print("%s 0x%02x 0x%02x 0x%02x \n", SLE_UART_SERVER_LOG, uuid->uuid[4], uuid->uuid[5],
            uuid->uuid[6], uuid->uuid[7]);
        sample_at_log_print("%s 0x%02x 0x%02x 0x%02x \n", SLE_UART_SERVER_LOG, uuid->uuid[8], uuid->uuid[9],
            uuid->uuid[10], uuid->uuid[11]);
        sample_at_log_print("%s 0x%02x 0x%02x 0x%02x \n", SLE_UART_SERVER_LOG, uuid->uuid[12], uuid->uuid[13],
            uuid->uuid[14], uuid->uuid[15]);
    }
}


// 以下是SSAP回调函数，用于处理MTU变化、服务启动、属性添加等事件
static void ssaps_mtu_changed_cbk(uint8_t server_id, uint16_t conn_id,  SsapcExchangeInfo *mtu_size,
    errcode_t status)
{
    sample_at_log_print("%s ssaps ssaps_mtu_changed_cbk callback server_id:%x, conn_id:%x, mtu_size:%x, status:%x\r\n",
        SLE_UART_SERVER_LOG, server_id, conn_id, mtu_size->mtuSize, status);
    if (g_sle_pair_hdl == 0) {
        g_sle_pair_hdl = conn_id + 1;
    }
}

static void ssaps_start_service_cbk(uint8_t server_id, uint16_t handle, errcode_t status)
{
    sample_at_log_print("%s start service cbk callback server_id:%d, handle:%x, status:%x\r\n", SLE_UART_SERVER_LOG,
        server_id, handle, status);
}
static void ssaps_add_service_cbk(uint8_t server_id, SleUuid *uuid, uint16_t handle, errcode_t status)
{
    sample_at_log_print("%s add service cbk callback server_id:%x, handle:%x, status:%x\r\n", SLE_UART_SERVER_LOG,
        server_id, handle, status);
    sle_uart_uuid_print(uuid);
}
static void ssaps_add_property_cbk(uint8_t server_id, SleUuid *uuid, uint16_t service_handle,
    uint16_t handle, errcode_t status)
{
    sample_at_log_print("%s add property cbk callback server_id:%x, service_handle:%x,handle:%x, status:%x\r\n",
        SLE_UART_SERVER_LOG, server_id, service_handle, handle, status);
    sle_uart_uuid_print(uuid);
}
static void ssaps_add_descriptor_cbk(uint8_t server_id, SleUuid *uuid, uint16_t service_handle,
    uint16_t property_handle, errcode_t status)
{
    sample_at_log_print("%s add descriptor cbk callback server_id:%x, service_handle:%x, property_handle:%x, \
        status:%x\r\n", SLE_UART_SERVER_LOG, server_id, service_handle, property_handle, status);
    sle_uart_uuid_print(uuid);
}
static void ssaps_delete_all_service_cbk(uint8_t server_id, errcode_t status)
{
    sample_at_log_print("%s delete all service callback server_id:%x, status:%x\r\n", SLE_UART_SERVER_LOG,
        server_id, status);
}
static errcode_t sle_ssaps_register_cbks(SsapsReadRequestCallback ssaps_read_callback, SsapsWriteRequestCallback
    ssaps_write_callback)
{
    errcode_t ret;
    SsapsCallbacks ssaps_cbk = {0};
    ssaps_cbk.addServiceCb = ssaps_add_service_cbk;
    ssaps_cbk.addPropertyCb = ssaps_add_property_cbk;
    ssaps_cbk.addDescriptorCb = ssaps_add_descriptor_cbk;
    ssaps_cbk.startServiceCb = ssaps_start_service_cbk;
    ssaps_cbk.deleteAllServiceCb = ssaps_delete_all_service_cbk;
    ssaps_cbk.mtuChangedCb = ssaps_mtu_changed_cbk;
    ssaps_cbk.readRequestCb = ssaps_read_callback;
    ssaps_cbk.writeRequestCb = ssaps_write_callback;
    ret = SsapsRegisterCallbacks(&ssaps_cbk);
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle_ssaps_register_cbks,ssaps_register_callbacks fail :%x\r\n", SLE_UART_SERVER_LOG,
            ret);
        return ret;
    }
    return ERRCODE_SLE_SUCCESS;
}

static errcode_t sle_uuid_server_service_add(void)
{
    errcode_t ret;
    SleUuid service_uuid = {0};
    sle_uuid_setu2(SLE_UUID_SERVER_SERVICE, &service_uuid);
    ret = SsapsAddServiceSync(g_server_id, &service_uuid, 1, &g_service_handle);
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle uuid add service fail, ret:%x\r\n", SLE_UART_SERVER_LOG, ret);
        return ERRCODE_SLE_FAIL;
    }
    return ERRCODE_SLE_SUCCESS;
}

static errcode_t sle_uuid_server_property_add(void)
{
    errcode_t ret;
    SsapsPropertyInfo property = {0};
    SsapsDescInfo descriptor = {0};
    uint8_t ntf_value[] = { 0x01, 0x02 };

    property.permissions = SLE_UUID_TEST_PROPERTIES;
    property.operateIndication = SLE_UUID_TEST_OPERATION_INDICATION;
    sle_uuid_setu2(SLE_UUID_SERVER_NTF_REPORT, &property.uuid);
    property.valueLen = OCTET_BIT_LEN;
    property.value = (uint8_t *)osal_vmalloc(sizeof(g_sle_property_value));
    
    if (property.value == NULL) {
        return ERRCODE_SLE_FAIL;
    }
    if (memcpy_s(property.value, sizeof(g_sle_property_value), g_sle_property_value,
        sizeof(g_sle_property_value)) != EOK) {
        osal_vfree(property.value);
        return ERRCODE_SLE_FAIL;
    }
    ret = SsapsAddPropertySync(g_server_id, g_service_handle, &property,  &g_property_handle);
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle uart add property fail, ret:%x\r\n", SLE_UART_SERVER_LOG, ret);
        osal_vfree(property.value);
        return ERRCODE_SLE_FAIL;
    }
    descriptor.permissions = SLE_UUID_TEST_DESCRIPTOR;
    descriptor.type = SSAP_DESCRIPTOR_CLIENT_CONFIGURATION;
    descriptor.operateIndication = SLE_UUID_TEST_OPERATION_INDICATION;
    descriptor.value = (uint8_t *)osal_vmalloc(sizeof(ntf_value));
    if (descriptor.value == NULL) {
        osal_vfree(property.value);
        return ERRCODE_SLE_FAIL;
    }
    if (memcpy_s(descriptor.value, sizeof(ntf_value), ntf_value, sizeof(ntf_value)) != EOK) {
        osal_vfree(property.value);
        osal_vfree(descriptor.value);
        return ERRCODE_SLE_FAIL;
    }
    ret = SsapsAddDescriptorSync(g_server_id, g_service_handle, g_property_handle, &descriptor);
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle uart add descriptor fail, ret:%x\r\n", SLE_UART_SERVER_LOG, ret);
        osal_vfree(property.value);
        osal_vfree(descriptor.value);
        return ERRCODE_SLE_FAIL;
    }
    osal_vfree(property.value);
    osal_vfree(descriptor.value);
    return ERRCODE_SLE_SUCCESS;
}

static errcode_t sle_uart_server_add(void)
{
    errcode_t ret;
    sle_uuid_t app_uuid = {0};

    sample_at_log_print("%s sle uart add service in\r\n", SLE_UART_SERVER_LOG);
    app_uuid.len = sizeof(g_sle_uuid_app_uuid);
    if (memcpy_s(app_uuid.uuid, app_uuid.len, g_sle_uuid_app_uuid, sizeof(g_sle_uuid_app_uuid)) != EOK) {
        return ERRCODE_SLE_FAIL;
    }
    ssapsRegisterServer(&app_uuid, &g_server_id);

    if (sle_uuid_server_service_add() != ERRCODE_SLE_SUCCESS) {
       SsapsUnregisterServer(g_server_id);
        return ERRCODE_SLE_FAIL;
    }
    if (sle_uuid_server_property_add() != ERRCODE_SLE_SUCCESS) {
        SsapsUnregisterServer(g_server_id);
        return ERRCODE_SLE_FAIL;
    }
    sample_at_log_print("%s sle uart add service, server_id:%x, service_handle:%x, property_handle:%x\r\n",
        SLE_UART_SERVER_LOG, g_server_id, g_service_handle, g_property_handle);
    ret = SsapsStartService(g_server_id, g_service_handle);
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle uart add service fail, ret:%x\r\n", SLE_UART_SERVER_LOG, ret);
        return ERRCODE_SLE_FAIL;
    }
    sample_at_log_print("%s sle uart add service out\r\n", SLE_UART_SERVER_LOG);
    return ERRCODE_SLE_SUCCESS;
}

/**
 * device通过handle向host发送数据：report
 * @param data 指向要发送的数据的指针。
 * @param len 要发送的数据长度。
 * @return 操作结果码。
 */
errcode_t sle_uart_server_send_report_by_handle(const uint8_t *data, uint8_t len)
{
    SsapsNtfInd param = {0};// 定义通知指示参数结构体。
    uint8_t receive_buf[UART_BUFF_LENGTH] = { 0 }; // 定义接收缓冲区，最大接收长度。
    param.handle = g_property_handle; // 设置属性句柄
    param.type = SSAP_PROPERTY_TYPE_VALUE;// 设置属性类型。
    param.value = receive_buf;// 设置属性值。
    param.valueLen = len+1;// 设置属性值长度。
    if (memcpy_s(param.value, param.valueLen, data, len) != EOK) {//复制数据到缓冲区。
        return ERRCODE_SLE_FAIL;// 如果复制失败，返回失败码。
    }
    return  SsapsNotifyIndicate(g_server_id, g_sle_conn_hdl, &param);// 发送通知指示。
}


/**
 * 连接状态改变时的回调函数。
 * @param conn_id 连接ID。
 * @param addr 连接设备的地址。
 * @param conn_state 连接状态。
 * @param pair_state 配对状态。
 * @param disc_reason 断开原因。
 */
static void sle_connect_state_changed_cbk(uint16_t conn_id, const SleAddr *addr,
    SleAcbStateType conn_state, SlePairStateType pair_state, SleDiscReasonType disc_reason)
{
    uint8_t sle_connect_state[] = "sle_dis_connect";// 断开连接时发送的状态信息。
    sample_at_log_print("%s connect state changed callback conn_id:0x%02x, conn_state:0x%x, pair_state:0x%x, \
        disc_reason:0x%x\r\n", SLE_UART_SERVER_LOG,conn_id, conn_state, pair_state, disc_reason);// 打印连接状态改变日志。
    sample_at_log_print("%s connect state changed callback addr:%02x:**:**:**:%02x:%02x\r\n", SLE_UART_SERVER_LOG,
        addr->addr[BT_INDEX_0], addr->addr[BT_INDEX_4]);// 打印设备地址日志。
    if (conn_state == OH_SLE_ACB_STATE_CONNECTED) {
        g_sle_conn_hdl = conn_id;// 如果连接状态为连接，更新连接句柄
      
    } else if (conn_state == OH_SLE_ACB_STATE_DISCONNECTED) {// 如果连接状态为断开。
        g_sle_conn_hdl = 0;// 重置连接句柄。
        g_sle_pair_hdl = 0;// 重置配对句柄。
        if (g_sle_uart_server_msg_queue != NULL) { // 如果消息队列不为空。
            g_sle_uart_server_msg_queue(sle_connect_state, sizeof(sle_connect_state)); // 发送断开连接消息。
        }

        /*重新启动广播*/
        errcode_t ret = sle_uart_server_adv_init();
        if (ret != ERRCODE_SLE_SUCCESS) {
            sample_at_log_print("%s Failed to re-initiate advertising after disconnection, error code: %x\r\n",
                SLE_UART_SERVER_LOG, ret);// 打印广播失败日志。
        }
    }
}



/**
 * 配对完成时的回调函数。
 * @param conn_id 连接ID。
 * @param addr 连接设备的地址。
 * @param status 配对状态。
 */
static void sle_pair_complete_cbk(uint16_t conn_id, const SleAddr *addr, errcode_t status)
{
    sample_at_log_print("%s pair complete conn_id:%02x, status:%x\r\n", SLE_UART_SERVER_LOG,
        conn_id, status);// 打印配对完成日志。
    sample_at_log_print("%s pair complete addr:%02x:**:**:**:%02x:%02x\r\n", SLE_UART_SERVER_LOG,
        addr->addr[BT_INDEX_0], addr->addr[BT_INDEX_4]);// 打印配对完成日志。
    g_sle_pair_hdl = conn_id + 1;// 更新配对句柄。

}



/**
 * 注册连接相关的回调函数。
 * @return 操作结果码。
 */
static errcode_t sle_conn_register_cbks(void)
{
    errcode_t ret;
    SleConnectionCallbacks conn_cbks = {0};// 定义连接回调结构体。
    conn_cbks.connectStateChangedCb = sle_connect_state_changed_cbk;// 设置连接状态改变回调。
    conn_cbks.pairCompleteCb = sle_pair_complete_cbk;// 设置配对完成回调。
    ret = SleConnectionRegisterCallbacks(&conn_cbks);// 注册连接回调。
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle_conn_register_cbks,sle_connection_register_callbacks fail :%x\r\n",
        SLE_UART_SERVER_LOG, ret);// 打印注册失败日志。
        return ret;// 返回失败码。
    }
    return ERRCODE_SLE_SUCCESS;// 返回成功码。
}



void ssaps_read_request_callbacks(uint8_t server_id, uint16_t conn_id, ssaps_req_read_cb_t *read_cb_para,
    errcode_t status){
        (void)server_id;
        (void)conn_id;
        (void)read_cb_para;
        (void)status;

    }

void ssaps_write_request_callbacks(uint8_t server_id, uint16_t conn_id, ssaps_req_write_cb_t *write_cb_para,
    errcode_t status){
      (void)server_id;
        (void)conn_id;
        (void)status;
         write_cb_para->value[write_cb_para->length-1] = '\0';
   printf("client_send_data: %s\r\n",write_cb_para->value);

    }


/* 初始化uuid server */
/**
 * 初始化UUID服务器。
 * @return 操作结果码。
 */
errcode_t sle_uart_server_init()
{
    errcode_t ret;
    ret = sle_uart_announce_register_cbks();// 注册广播回调。
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle_uart_server_init,sle_uart_announce_register_cbks fail :%x\r\n",
        SLE_UART_SERVER_LOG, ret);// 打印广播注册失败日志。
        return ret;// 返回失败码。
    }
    ret = sle_conn_register_cbks(); // 注册连接回调。
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle_uart_server_init,sle_conn_register_cbks fail :%x\r\n", SLE_UART_SERVER_LOG, ret);// 打印连接注册失败日志。
        return ret;// 返回失败码。
    }
    ret = sle_ssaps_register_cbks(ssaps_read_request_callbacks, ssaps_write_request_callbacks);// 注册SSAP回调。
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle_uart_server_init,sle_ssaps_register_cbks fail :%x\r\n", SLE_UART_SERVER_LOG, ret);// 打印SSAP注册失败日志。
        return ret;// 返回失败码。
    }
    ret = EnableSle();// 启用SLE。
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle_uart_server_init,enable_sle fail :%x\r\n", SLE_UART_SERVER_LOG, ret);// 打印SLE启用失败日志。
        return ret;// 返回失败码。
    }

    /*重新广播*/
    ret = sle_uart_server_adv_init();
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle_uart_server_init,sle_uart_server_adv_init fail :%x\r\n", SLE_UART_SERVER_LOG, ret);// 打印广播初始化失败日志。
        return ret; // 返回失败码。
    }
    sample_at_log_print("%s init ok\r\n", SLE_UART_SERVER_LOG);// 打印初始化成功日志。
    return ERRCODE_SLE_SUCCESS;// 返回成功码。
}



/**
 * 启用服务器回调函数。
 * @return 操作结果码。
 */
errcode_t sle_enable_server_cbk(void)
{
    errcode_t ret;
    ret = sle_uart_server_add(); // 添加SLE服务。
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle_uart_server_init,sle_uart_server_add fail :%x\r\n", SLE_UART_SERVER_LOG, ret);// 打印服务添加失败日志。
        return ret; // 返回失败码。
    }
    ret = sle_uart_server_adv_init(); // 重新广播。
    if (ret != ERRCODE_SLE_SUCCESS) {
        sample_at_log_print("%s sle_uart_server_init,sle_uart_server_adv_init fail :%x\r\n", SLE_UART_SERVER_LOG, ret);// 打印广播初始化失败日志。
        return ret; // 返回失败码。
    }
    return ERRCODE_SLE_SUCCESS;// 返回成功码。
}


// 注册串口消息队列
void sle_uart_server_register_msg(sle_uart_server_msg_queue sle_uart_server_msg)
{
    g_sle_uart_server_msg_queue = sle_uart_server_msg;
}


// 向串口发送数据的函数
int uart_sle_send_data(uint8_t *data,uint8_t length){
    int ret;
    ret = sle_uart_server_send_report_by_handle(data,length);
    return ret ;
}


// 串口接收数据的回调函数
static void server_uart_rx_callback(const void *buffer, uint16_t length, bool error)
{
    errcode_t ret;
    

    if (error) {
        printf("Error receiving data, length: %d\n", length);
        return;
    }

    if (length == 0) {
        printf("Received zero-length frame, no data available.\n");
        return;
    }

    printf("UART RX callback triggered, Received Response Frame (%d bytes): ", length);
    for (int i = 0; i < length; i++) {
        printf("%02X ", ((unsigned char *)buffer)[i]);  /*以十六进制形式打印应答帧*/
    }
    printf("\n");

    if (length >= 5) { 
        uint8_t secondDataByte = ((unsigned char *)buffer)[4]; // 获取第二个数据字节
        printf("Second data byte (water status): %02X\n", secondDataByte); // 打印第二个数据字节

        /*判断是否发送水浸*/
        if (secondDataByte == 0x02) { 
            printf("Water immersion detected!\n");// 打印水浸检测到的信息
            uart_send_to_client(1); // 调用函数发送水浸信号
        } else {
            printf("No water immersion.\n");// 打印无水浸的信息
            uart_send_to_client(0); // 调用函数发送无水浸信号
        }
    } else {
        printf("Response frame is too short to contain data.\n");
    }
}


// 初始化串口配置的函数
static void uart_init_config(void)
{
    uart_attr_t attr = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_BIT_8,
        .stop_bits = UART_STOP_BIT_1,
        .parity = UART_PARITY_NONE
    };

    uart_pin_config_t pin_config = {
        .tx_pin = 0,
        .rx_pin = 0,
        .cts_pin = PIN_NONE,
        .rts_pin = PIN_NONE
    };
  

    uapi_uart_deinit(1); /*反初始化串口1*/

    /*配置 UART 参数*/
    IotUartAttribute g_uart_cfg = {9600, 8, 1, IOT_UART_PARITY_NONE, 100, 100, 0}; 
    if (IoTUartInit(1, &g_uart_cfg) != 0) {
        printf("Failed to initialize UART1, return code: %d\n", IoTUartInit(1, &g_uart_cfg));
        return;
    }
    printf("UART1 initialized successfully.\n");

    /*注册 RX 回调*/
    if (uapi_uart_register_rx_callback(1, UART_RX_CONDITION_FULL_OR_SUFFICIENT_DATA_OR_IDLE, 16, server_uart_rx_callback) != 0) {
        printf("Failed to register RX callback for UART1\n");
        return;
    }
    printf("RX callback registered successfully for UART1.\n");
}


// SLE任务处理函数
static void SleTask( char* arg)
{
    (void)arg;
    usleep(1000000);
    uart_init_config();
    sle_uart_server_init();
    return NULL;
}


/*任务处理函数 */
static void* SLETask(const char* arg) 
{ 
    (void)arg; 
    uart_init_config(); /*配置串口1*/
    sle_uart_server_init();
    while(1){
        /*发送 Modbus 请求帧*/
        printf("Sending Modbus request frame...\n");
        IoTUartWrite(1, modbusRequest, sizeof(modbusRequest));

        /*等待一段时间以便接收应答*/
        usleep(5000000); 
        printf("Waiting for response...\n");
    }
    return NULL; 
} 


//向客户端发送数据的函数
// status: 表示水浸状态，1表示水浸，0表示无水浸
void uart_send_to_client(int status){
    if(status==1){
        const char* data_to_send = "11 end";// 定义发送的数据,此时浸水
        uint8_t data_len = strlen(data_to_send); // 计算数据长度
        printf("11 end");
        int uartslesend=uart_sle_send_data((const uint8_t *)data_to_send,data_len);// 调用函数发送数据
    }
    else{
        const char* data_to_send = "10 end";// 定义发送的数据
        uint8_t data_len = strlen(data_to_send); // 计算数据长度
        printf("10 end"); // 打印发送的数据
        int uartslesend=uart_sle_send_data((const uint8_t *)data_to_send,data_len);// 调用函数发送数据
    }
    printf("send success\n");// 打印发送成功的信息
}



// SLE服务器示例函数
static void SleServerExample(void)
{
   osThreadAttr_t attr = {0}; // 创建线程属性结构体

    attr.name = "SLETask"; // 设置线程名称
    attr.attr_bits = 0U; // 设置线程属性位
    attr.cb_mem = NULL; // 设置回调内存
    attr.cb_size = 0U; // 设置回调大小
    attr.stack_mem = NULL; // 设置栈内存
    attr.stack_size = 2048; // 设置栈大小
    attr.priority = osPriorityNormal; // 设置线程优先级

    // 创建SLETask线程
    if (osThreadNew((osThreadFunc_t)SLETask, NULL, &attr) == NULL) 
    { 
        printf("[SleExample] Falied to create SleTask!\n"); // 打印创建线程失败的信息
    } else {
        printf("[SleExample]  create SleTask successfully !\n"); // 打印创建线程成功的信息
    }
}

SYS_RUN(SleServerExample); // if test add it

